
open Glob.Bin

let change_dir () =
    let dir = !//"tmp"//(string_of_int (Random.int max_int)) in
    Unix.mkdir dir 0o740;
    Sys.chdir dir;
    dir
;;

let create ?(reverse_vertical_order=false) m =
(*    let tabular_def = String.make (Array.length m) 'c' in*)
(*    let n = Array.length m in*)
    let nx = Array.length m and ny = Array.length m.(0) in
    let tabular_def = List.fold_left (fun acc _ -> acc^"|c") "" (1--nx) in
    let str = ref ("\\begin{tabular}"^"{"^tabular_def^"|}") in
    let add str2 = str := !str ^ str2 in
    let y = ref (if reverse_vertical_order then ny-1 else 0) in
    while ( 0 <= !y && !y < ny) do
        add "\n\\hline\n";
        for ix = 0 to nx-1 do
            if ix <> 0 then add " & ";
            add m.(ix).(!y);
        done;
        add "\\\\";
        if reverse_vertical_order then decr y else incr y;
    done;
    add "\\hline\n";
    add "\\end{tabular}";
    !str
;;

let make ?(landscape=false) ?(reverse_vertical_order=false) 
        ?(title="") ~view_command m =
  print_endline "go to tmp...";
  let old_dir = Sys.getcwd () in
  let dir = change_dir () in
  print_endline "creating table...";
  let table = create  ~reverse_vertical_order m in
  let file_name = (*dir //*) "table.tex" in
  print_endline "writing table to file...";
  let file = open_out file_name in
  let print str = output_string file str in
  print "\\documentclass{article}\n";
  print
  "\\usepackage[top=1.5cm,bottom=1.5cm,left=1.5cm,right=1.5cm]{geometry}";
  if landscape then (
(*          print "\\usepackage[landscape]{geometry}";*)
          print "\\usepackage{rotating}";
          );
  print "\\begin{document}\n";
  if landscape then (
          print "\\begin{sidewaystable}\n")
  else (
          print "\\begin{table}\n");
  print table;
  if(title<>"") then (
          print (Printf.sprintf "\\caption{%s}" title));
  if landscape then (
          print "\\end{sidewaystable}\n")
  else (
          print "\\end{table}\n");
  output_string file "\\end{document}\n";
  close_out file;
  Sys.command ("yse | latex "^file_name);
  Sys.command "dvips table.dvi -o table.ps";
  Sys.chdir old_dir;
  Sys.command (view_command^" "^(dir//"table.ps"));
  Sys.command ("rm -rf "^dir);
  ()
;;

